<template>
	<view class="container" v-if="indexData">
		<myNavigate changecity="getcity" :mark="mark" :message="msg" :cityname="currCity"></myNavigate>
		<!-- 小程序头部兼容 -->
		<!-- <view class="mp-search-box">
			<input class="ser-input" type="text" value="输入关键字搜索" />
		</view> -->
		<!-- 头部轮播 -->
		<view class="carousel-section">
			<!-- 标题栏和状态栏占位符 -->
			<view class="titleNview-placing"></view>
			<!-- 背景色区域 -->
			<view class="titleNview-background" :style="{backgroundColor:'#ee5b25'}"></view>
			<swiper class="carousel" circular @change="swiperChange">
				<swiper-item v-for="(item, index) in indexData.moreSale" :key="index" class="carousel-item" @click="navToDetailPage(item)">
					<image :src="item.goodsImg" />
				</swiper-item>
			</swiper>
			<!-- 自定义swiper指示器 -->
			<view class="swiper-dots">
				<text class="num">{{swiperCurrent+1}}</text>
				<text class="sign">/</text>
				<text class="num">{{indexData.moreSale.length}}</text>
			</view>
		</view>

		<!-- 分类 -->
		<view class="cate-section">
			<block v-for="(item,index) in indexData.cats" :key='index'>
				<view class="cate-item" @click="navCate(item)">
					<image :src="item.catImg"></image>
					<text>{{item.simpleName}}</text>
				</view>
			</block>
		</view>
		<block v-if="indexData.img">
			<view class="imageAd">
				<imageAd :imgs='indexData.img' v-if="indexData"></imageAd>
			</view>
		</block>
		
		<!-- 暂未开放的模块 -->
		<view class="rechang-imgs" >
			<image class="re-icon"  @click="navCate({catId:448})" src="/static/icon/index_icon_mo_01.png" mode=""></image>
			<image class="re-icon" @click="toRouter('/pages/index/mobile')" src="/static/icon/index_icon_mo_02.png" mode=""></image>
			<image class="re-icon" @click="toRouter('/pages/index/ticket')" src="/static/icon/index_icon_mo_03.png" mode=""></image>
			<image class="re-icon" @click="toRouter('/pages/index/insure')" src="/static/icon/index_icon_mo_04.png" mode=""></image>
		</view>
		
		<!-- 美食生态 -->
		<view class="gua-imgs">
			<image class="gua-icon"  @click="toRouter('/pages/index/life')" src="/static/images/gua_index_row.png" mode=""></image>
		</view>
		<!-- 猜你喜欢 -->
		<view class="f-header m-t">
			<image src="https://www.ggshop1688.com/upload/api-img/bgImage.jpg"></image>
			<!-- <view class="tit-box">
				<text class="tit">精品推荐</text>
				<text class="tit2">Recommended</text>
			</view> -->
			<!-- <text class="yticon icon-you"></text> -->
		</view>
		<goodsList :goodsList="goodslistData"></goodsList>
		<uni-load-more v-if="needLoad" :status="loadingType"></uni-load-more>
		<!-- #ifdef APP-PLUS -->
		<view class="invitedBox" @click="showInvited" v-if="inviteds && inviteds.length">
			<view class="boxInner">
				<view class="circle">
					{{inviteds.length}}
				</view>
				<uniIcons type="chat" color="#fff"></uniIcons>
			</view>
		</view>
		<!-- #endif -->

		<modal ref="invited" title="拼团邀请" titlebg='#ee5b25'>
			<scroll-view scroll-y="true" class="invitedList">
				<!---->
				<block v-if="inviteds && inviteds.length">
					<radio-group @change="radioChange">
						<view class="invitedItem" v-for="(invited ,index) in inviteds" :key="index">
							<image :src="invited.userPhoto" class="inviterPic"></image>
							<view class="invitedText">
								{{invited.userName}}邀请你参加{{invited.name}}拼团
							</view>
							<radio :value="index" color='#fd4542' :checked="index === currentPin"></radio>
						</view>

					</radio-group>
				</block>
				<view class="noInvited" v-else>
					当前暂无邀请
				</view>
			</scroll-view>
			<view class="agreePin" @click="toTourList">
				参加拼团
			</view>
		</modal>
	</view>
</template>

<script>
	import uniLoadMore from '@/components/uni-load-more/uni-load-more.vue';
	import loteryCoupon from "@/components/lotteryCoupon/lotteryCoupon"
	import modal from "@/components/myModal/myModal.vue"
	import goodsList from '@/components/goodsCardGrid/goodsCardGrid.vue'
	import imageAd from '@/components/imageAd/imageAd'
	import uniIcons from "@/components/uni-icons/uni-icons.vue"
	import myNavigate from "@/components/myNavigateBar/myNavigateBar.vue"
	import amap from '@/common/amap-wx.js';
	export default {
		components: {
			uniLoadMore,
			loteryCoupon,
			modal,
			imageAd,
			goodsList,
			uniIcons,
			myNavigate
		},
		data() {
			return {
				version: 6,
				isdone: false,
				loading: false,
				loadingType: 'more',
				needLoad: true,
				page: 1,
				mark: 0,
				key: 'e09665ab2c8f03d67d0550e32d605943',
				currCity: '',
				longitude: '',
				latitude: '',
				currentPin: 0,
				indexData: null,
				goodslistData: [],
				inviteds: [],
				titleNViewBackground: '',
				swiperCurrent: 0,
				swiperLength: 0,
				carouselList: [],
				goodsList: [],
				beenInvited: null,
				msg: 0,
			};
		},
		onLoad() {
			let that = this;
			let platform;
			uni.getSystemInfo({
				success: function(res) {
					console.log(res)
					platform = res.platform
				}
			})
			let data = {
				clientType: platform
			}
			that.$Request.request('/api/index/appVersion', 'GET', data).then(res => {
				if (res.status == 1) {
					if (that.version < res.data.version) {
						uni.showModal({
							tilte: '温馨提示',
							content: '版本变更！请前往更新',
							showCancel: false,
							success: function(result) {
								if (result.confirm) {
									uni.showLoading({
										mask: true,
										title: '更新中,请等待更新完毕'
									})
									uni.downloadFile({
										url: res.data.downloadUrl,
										success: (downloadResult) => {
											uni.hideLoading()
											if (downloadResult.statusCode === 200) {
												plus.runtime.openFile(downloadResult.tempFilePath)
											}
										}
									})
								}
							}
						})
					}
				}
			})
			uni.getLocation({
				type: 'wgs84',
				geocode: true,
				success: function(res) {
					console.log(res)
					//#ifdef APP-PLUS
						getApp().globalData.globa_latitude = res.latitude;
						getApp().globalData.globa_longitude = res.longitude;
						that.currCity = res.address.city;
						that.locationname = res.address.city;
						uni.setStorageSync('mycity', that.currCity)
					//#endif

					//#ifdef MP-WEIXIN
					getApp().globalData.globa_latitude = res.latitude;
					getApp().globalData.globa_longitude = res.longitude;
					var amapPlugin = new amap.AMapWX({
						key: that.key
					});
					amapPlugin.getRegeo({
						location: '' + getApp().globalData.globa_longitude + ',' + getApp().globalData.globa_latitude + '',
						success: (data) => {
							console.log(data)
							that.currCity = data[0].regeocodeData.addressComponent.city;
							console.log(that.currCity )
							uni.setStorageSync('mycity', that.currCity)
						}
					});

					//#endif
				},
				fail: function(res) {
					console.log('111')
					console.log(res)
					that.currCity = '获取定位'
				}
			})

			this.loadgoodslist()
		},

		onShow() {
			// this.page = 1 ;
			// this.isdone = false;
			// this.goodslistData = []
			this.loadData();
			let hasLogin = uni.getStorageSync('userInfo') ? true : false

			// if (hasLogin) {
			// 	this.loadInvited();//原始版本加载被邀请参与拼团数据
			// }

			this.unredmessage()
		},
		// onHide() {
		// 	clearInterval(this.beenInvited)
		// },
		// onUnload() {
		// 	clearInterval(this.beenInvited)
		// },
		methods: {
			// 跳转
			toRouter(url){
				uni.navigateTo({
					url: url
				})
			},
			// 暂未开放
			showTips(){
				this.$api.msg('暂未开放该功能')
			},
			
			onReachBottom() {
				let that = this;
				if (that.isdone) {
					return false;
				}
				that.loading = true;
				that.page++
				that.loadingType = 'loading'
				that.loadgoodslist()
			},
			loadgoodslist() {
				let that = this;
				if (that.isdone) {
					return false;
				}
				that.$Request.request('/api/goods/likes', 'GET', {
					p: that.page
				}).then(res => {
					if (res.status == 1) {
						res.data.like.forEach(item => {
							that.goodslistData.push(item)
						})
						that.loadingType = 'more'
						if (res.data.like.length == 0) {
							that.loading = true;
							that.isdone = true;
							that.loadingType = 'noMore'
						}
						console.log(that.goodslistData)
						that.goodslistData.length == 0 ? [this.showempty = true, this.needLoad = false] : [this.showempty = false, this
							.needLoad =
							true
						]
					}
				}).catch(err => {
					console.log(err)
				})
			},
			unredmessage() {
				let that = this;
				that.$Request.request('/api/message/list', 'GET', {}).then(res => {
					if (res.status == 1) {
						that.msg = res.data.unreadCount
					}
				}).catch(err => {
					console.log(err)
				})
			},
			getcity(data) {
				console.log(data)
			},
			tolimitbag() {
				uni.navigateTo({
					url: '/district/limitbag/limitbag'
				})
			},
			loadInvited() {
				this.beenInvited = setInterval(() => {
					let that = this
					that.$Request.request('/api/pintuan/lookInvitePintuan', 'GET', {}).then(res => {
						if (res.status == 1) {
							console.log(res)
							this.inviteds = res.data
						}
					}).catch(err => {
						console.log(err)
					})
				}, 8000)
			},
			navWithLogin() {
				let hasToken = uni.getStorageSync('userInfo') ? true : false
				if (!hasToken) {
					uni.navigateTo({
						url: '/pages/public/login'
					})
					return
				}
			},
			toTourList() {
				this.$refs.invited.close()
				let pin = this.inviteds[this.currentPin]
				let that = this
				that.$Request.request('/api/pintuan/alterInvitationStatus', 'POST', {
					inviteId: pin.inviteId
				}).then(res => {
					if (res.status == 1) {
						uni.navigateTo({
							url: '/subPackage/tourList/tourList?invitedId=' + pin.id
						})
					}
				}).catch(err => {
					console.log(err)
				})

			},
			showInvited() {
				this.$refs.invited.open()
			},
			radioChange(e) {
				this.currentPin = e.detail.value
			},
			//前往拼团列表
			toGroupbooking() {
				uni.navigateTo({
					url: '/pages/groupbooking/groupbooking'
				})
			},
			navCate(item) {
				let id = item.catId
				if(id == '447'){
					// return this.$api.msg('暂未开放该功能')
					return uni.navigateTo({
						url: '/pages/barter/list'
					})
				}

        console.log('item====>', item );
        if(id == '395'){
          return uni.navigateTo({
            url: '/pages/product/spike'
          })
        }

				uni.setStorageSync('postId', id)
        uni.switchTab({
					url: '/pages/category/category'
				})
			},
			/**
			 * 请求静态数据只是为了代码不那么乱
			 * 分次请求未作整合
			 */
			loadData() {
				let that = this
				that.$Request.request('/api/goods/getIndexInfo', 'GET', {}).then(res => {
					// console.log(res)
					if (res.status == 1) {
						that.indexData = res.data
					}
				}).catch(err => {
					console.log(err)
				})
				// let carouselList = await this.$api.json('carouselList');
				// this.titleNViewBackground = carouselList[0].background;
				// this.swiperLength = carouselList.length;
				// this.carouselList = carouselList;

				// let goodsList = await this.$api.json('goodsList');
				// this.goodsList = goodsList || [];
			},
			//轮播图切换修改背景色
			swiperChange(e) {
				const index = e.detail.current;
				this.swiperCurrent = index;
			},
			//详情页
			navToDetailPage(item) {
				//测试数据没有写id，用title代替
				// console.log(1111)
				let id = item.goodsId;
				// uni.navigateTo({
				// 	url: `/pages/product/product?id=${id}`
				// })
			},
		},
		// #ifndef MP
		// 标题栏input搜索框点击
		onNavigationBarSearchInputClicked: async function(e) {
			this.$api.msg('点击了搜索框');
		},
		//点击导航栏 buttons 时触发
		onNavigationBarButtonTap(e) {
			const index = e.index;
			if (index === 0) {
				this.$api.msg('点击了扫描');
			} else if (index === 1) {
				// #ifdef APP-PLUS
				const pages = getCurrentPages();
				const page = pages[pages.length - 1];
				const currentWebview = page.$getAppWebview();
				currentWebview.hideTitleNViewButtonRedDot({
					index
				});
				// #endif
				uni.navigateTo({
					url: '/pages/notice/notice'
				})
			}
		}
		// #endif
	}
</script>

<style lang="scss">
	.task button:after {
		border: none !important;
	}

	@import './index.scss';
</style>
